package com.xnyzc.lhy.mis.service.impl.cms.vehicle;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xnyzc.lhy.common.component.config.security.TokenUser;
import com.xnyzc.lhy.common.entity.Qw;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.util.*;
import com.xnyzc.lhy.mis.entity.dictionaries.OaSysDict;
import com.xnyzc.lhy.mis.entity.param.cms.vehicle.VehicleBrandParam;
import com.xnyzc.lhy.mis.entity.result.cms.veh.VehicleManageInfo;
import com.xnyzc.lhy.mis.entity.result.cms.veh.VehicleSeries;
import com.xnyzc.lhy.mis.entity.result.cms.veh.VehicleTypeSeries;
import com.xnyzc.lhy.mis.entity.vehicle.OaSysVehicle;
import com.xnyzc.lhy.mis.entity.vehicle.OaSysVehicleMdict;
import com.xnyzc.lhy.mis.entity.vehicle.OaVehicleSeries;
import com.xnyzc.lhy.mis.mapper.dictionaries.OaSysDictMapper;
import com.xnyzc.lhy.mis.mapper.vehicle.OaSysVehicleMapper;
import com.xnyzc.lhy.mis.mapper.vehicle.OaSysVehicleMdictMapper;
import com.xnyzc.lhy.mis.mapper.vehicle.OaVehicleSeriesMapper;
import com.xnyzc.lhy.mis.service.cms.vehicle.VehicleBrandService;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.logging.log4j.core.util.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;

/**
 * <p>
 * 车辆品牌相关
 * </p>
 *
 * @author wangshuo
 * @since 2019-08-23
 */
@Service
public class VehicleBrandServiceImpl implements VehicleBrandService {

    private static final String VEHICLE_OF_BRAND = "1";
    private static final String VEHICLE_OF_SERIES = "2";

    @Autowired
    private OaSysVehicleMdictMapper oaSysVehicleMdictMapper;

    @Autowired
    private OaVehicleSeriesMapper oaVehicleSeriesMapper;

    @Autowired
    private OaSysVehicleMapper oaSysVehicleMapper;

    @Autowired
    private OaSysDictMapper oaSysDictMapper;


    /**
     * 根据品牌名模糊查询品牌列表
     * @param brandName
     * @return
     */
    @Override
    public Rv getVehicleBrand(String brandName) {
       List<OaSysVehicleMdict> oaSysVehicleMdicts = oaSysVehicleMdictMapper.getVehicleBrand(brandName);
        return Rv.wrap(oaSysVehicleMdicts);
    }

    @Override
    public Rv getVehicleSeriesOfList(String brandId, String seriesName) {
        List<OaSysVehicleMdict> oaSysVehicleSeries = oaSysVehicleMdictMapper.getVehicleSeriesOfList(brandId,seriesName);
        return Rv.wrap(oaSysVehicleSeries);
    }


    /**
     * 新增车型信息
     * @param vehicleTypeSeries
     * @return
     */
    @Override
    public Rv addVehicleType(VehicleTypeSeries vehicleTypeSeries) {
        TokenUser tokenUser = TokenUtil.getTokenUser();
        Long tokenUserId = tokenUser.getTokenUserId();
        if(CheckUtil.objIsEmpty(tokenUser,tokenUserId)){
            throw PangException.create(EErrorCode.missingArg);
        }
        if(CheckUtil.objIsEmpty(vehicleTypeSeries)){
            throw PangException.create(EErrorCode.missingArg);
        }
        if(CheckUtil.objIsNotEmpty(vehicleTypeSeries.getExpand1())){
            OaSysVehicleMdict oaSysVehicleMdict = new OaSysVehicleMdict();
            oaSysVehicleMdict.setDeleted(0);
            oaSysVehicleMdict.setUpdateTime(new Date());
            oaSysVehicleMdict.setCreateTime(new Date());
            oaSysVehicleMdict.setName(vehicleTypeSeries.getName());
            //将中文品牌名转换成英文再提取首字符大写
            String pinyinName = convertChineseToFullSpell(vehicleTypeSeries.getName()).substring(0,1).toUpperCase();
            oaSysVehicleMdict.setTag(pinyinName);
            oaSysVehicleMdict.setDescription(vehicleTypeSeries.getDescription());
            oaSysVehicleMdict.setSort(BigDecimal.valueOf(0));
            oaSysVehicleMdict.setExpand1(vehicleTypeSeries.getExpand1());
            oaSysVehicleMdict.setCreateUser(tokenUserId);
            oaSysVehicleMdict.setUpdateUser(tokenUserId);
            oaSysVehicleMdict.setVersion(1L);
            oaSysVehicleMdict.setCode(RandomUtil.getRandomNumberStr(8));
            int insert = 0;
            String parentIds = "0"+","+"1"+",";
            if(vehicleTypeSeries.getExpand1().equals(VEHICLE_OF_BRAND)){
                //通过品牌名称查询该品牌是否已经存在
                QueryWrapper<OaSysVehicleMdict> mdictQueryWrapper = new QueryWrapper<>();
                mdictQueryWrapper.eq(OaSysVehicleMdict.NAME,vehicleTypeSeries.getName());
                mdictQueryWrapper.eq(OaSysVehicleMdict.EXPAND1,VEHICLE_OF_BRAND);
                OaSysVehicleMdict sqlBrandMdict = oaSysVehicleMdictMapper.selectOne(mdictQueryWrapper);
                if(CheckUtil.objIsNotEmpty(sqlBrandMdict)){
                    throw PangException.create(EErrorCode.vehicleIsExits);
                }
                oaSysVehicleMdict.setParentId("1");
                oaSysVehicleMdict.setParentIds(parentIds);
            }else if(vehicleTypeSeries.getExpand1().equals(VEHICLE_OF_SERIES)){
                oaSysVehicleMdict.setParentId(vehicleTypeSeries.getBrandNo());
                oaSysVehicleMdict.setParentIds(parentIds+vehicleTypeSeries.getBrandNo()+",");
            }else{
                OaSysVehicleMdict mdict = oaSysVehicleMdictMapper.selectById(vehicleTypeSeries.getSeriesNo());
                oaSysVehicleMdict.setParentId(vehicleTypeSeries.getSeriesNo());
                oaSysVehicleMdict.setParentIds(mdict.getParentIds()+vehicleTypeSeries.getSeriesNo()+",");
                oaSysVehicleMdict.setVehicleType(Integer.valueOf(vehicleTypeSeries.getVehicleType()));
                oaSysVehicleMdict.setVehSeatsNumber(vehicleTypeSeries.getVehSeatsNumber());
                oaSysVehicleMdict.setExpand3(mdict.getName()+vehicleTypeSeries.getName());
            }
            insert = oaSysVehicleMdictMapper.insert(oaSysVehicleMdict);
            return Rv.wrap(EErrorCode.success,insert);
        }
        return Rv.wrap();
    }

    /**
     * 获取车辆品牌列表
     *
     * @return
     */
    @Override
    public Rv getAssociatedBrandList(VehicleBrandParam vehicleBrandParam) {
        IPage iPage = new Page();
        iPage.setCurrent(vehicleBrandParam.getCurrent());
        iPage.setSize(vehicleBrandParam.getSize());
        List<VehicleManageInfo> associatedBrandList = oaSysVehicleMdictMapper.getAssociatedBrandList(iPage, vehicleBrandParam.getIsRelation(), vehicleBrandParam.getVehicleType(), vehicleBrandParam.getCode());
        if (!associatedBrandList.isEmpty() && !CollectionUtils.isEmpty(associatedBrandList)) {
            List<String> classBID = new ArrayList<>();
            for (int i = 0; i < associatedBrandList.size(); i++) {
                classBID.add(associatedBrandList.get(i).getParentId());
            }

            List<OaSysVehicleMdict> vehicleMdictB = this.findVehicleMdict(classBID, OaSysVehicleMdict.MDICT_ID);
            List<String> classAID = new ArrayList<>();
            for (int i = 0; i <vehicleMdictB.size() ; i++) {
                classAID.add(vehicleMdictB.get(i).getParentId());
            }
            List<OaSysVehicleMdict> vehicleMdictA = this.findVehicleMdict(classAID, OaSysVehicleMdict.MDICT_ID);

            JSONArray jsonArrayMdictA = JSONArray.parseArray(JSON.toJSONString(vehicleMdictA));
            JSONArray jsonArrayMdictB = JSONArray.parseArray(JSON.toJSONString(vehicleMdictB));
            JSONArray jsonArrayMdictC = JSONArray.parseArray(JSON.toJSONString(associatedBrandList));
            JSONArray vehicleSplicingData = VehicleManageServiceImpl.getVehicleSplicingData(
                    jsonArrayMdictA, jsonArrayMdictB, jsonArrayMdictC,
                    "vehicleCode1", "vehicleCode2", "vehicleCode3",
                    "brand", "model", "vehicleTypeName",
                    "code", "mdictId"
            );
            iPage.setRecords(vehicleSplicingData);
        }
        return Rv.wrap(EErrorCode.success, iPage);
    }

    /**
     * 查询车字典
     *
     * @return
     */
    private List<OaSysVehicleMdict> findVehicleMdict(List<String> inList, String findField) {
        //查询车字典数据
        QueryWrapper<OaSysVehicleMdict> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(findField, inList);
        queryWrapper.select(OaSysVehicleMdict.MDICT_ID, OaSysVehicleMdict.PARENT_ID, OaSysVehicleMdict.CODE, OaSysVehicleMdict.NAME);
        return oaSysVehicleMdictMapper.selectList(queryWrapper);
    }




    /**
     * 获取车辆品牌列表
     *
     * @return
     */
    @Override
    public Rv getVehicleBrandList(VehicleBrandParam vehicleBrandParam) {
        QueryWrapper<OaSysVehicleMdict> queryWrapper = new QueryWrapper<>();
        List<OaSysVehicleMdict> list = new ArrayList<>();
        if (!StringUtils.isEmpty(vehicleBrandParam.getName())) {
            //queryWrapper.like(OaSysVehicleMdict.NAME, vehicleBrandParam.getName());
            queryWrapper.eq(OaSysVehicleMdict.PARENT_ID, 1);
            List<OaSysVehicleMdict> mditList = oaSysVehicleMdictMapper.selectList(queryWrapper);
            if (mditList.isEmpty()) {
                return Rv.wrap(EErrorCode.dataCheckErr);
            }
            QueryWrapper<OaSysVehicleMdict> mdictQueryWrapper = new QueryWrapper<>();
            mdictQueryWrapper.like(OaSysVehicleMdict.PARENT_IDS, "," + mditList.get(0).getMdictId() + ",");
            list = oaSysVehicleMdictMapper.selectList(mdictQueryWrapper);
            list.add(mditList.get(0));
        } else {
            list = oaSysVehicleMdictMapper.selectList(queryWrapper);
        }
        List<Map<String, Object>> menuMapList = ListToTreeUtil.getVehicleMdictList(list);
        //转成树
        JSONArray menuResultList = ListToTreeUtil.listToTree(JSONArray.parseArray(JSON.toJSONString(menuMapList)), "id", "pId", "children");
        return Rv.wrap(EErrorCode.success, menuResultList);
    }

    /**
     * 类型关联车系
     *
     * @return
     */
    @Override
    public Rv getVehicleSeries(VehicleBrandParam vehicleBrandParam) {
        //Long userId = TokenUtil.getTokenUserId();
        //String tag = TokenUtil.getTag();
        //String vehicleType = vehicleBrandParam.getVehicleType();
        //if (StringUtils.isEmpty(vehicleBrandParam.getCode())) {
        //    throw PangException.create(EErrorCode.missingArg);
        //}
        //String[] array = vehicleBrandParam.getCode().split(",");
        //List<String> mlist = Arrays.asList(array);
        //Date date = new Date();
        //List<String> removeList = new ArrayList<>();
        //List<String> codeList = new ArrayList<>();
        //QueryWrapper<OaSysVehicleMdict> queryWrapper = new QueryWrapper<>();
        //queryWrapper.in(OaSysVehicleMdict.CODE, mlist);
        //queryWrapper.eq(OaSysVehicleMdict.EXPAND1, 3);
        //List<OaSysVehicleMdict> mdictsList = oaSysVehicleMdictMapper.selectList(queryWrapper);
        //for (OaSysVehicleMdict mdict : mdictsList) {
        //    codeList.add(mdict.getCode());
        //}
        //// 全部已选
        //List<OaVehicleSeries> vehicleSeriesList = getVehicleSeriesList(codeList);
        //for (OaVehicleSeries series : vehicleSeriesList) {
        //    series.setUpdateUser(userId);
        //    series.setUpdateTime(date);
        //    series.setVehicleType(Integer.parseInt(vehicleType));
        //    series.setTag(tag);
        //    oaVehicleSeriesMapper.updateById(series);
        //    removeList.add(series.getCode());
        //}
        //codeList.removeAll(removeList);
        //if (!codeList.isEmpty()) {
        //    for (String code : codeList) {
        //        OaVehicleSeries series = new OaVehicleSeries();
        //        series.setLinkedId(IDUtil.nextId());
        //        series.setVehicleType(Integer.parseInt(vehicleType));
        //        series.setCode(code);
        //        series.setUpdateTime(date);
        //        series.setUpdateUser(userId);
        //        series.setCreateTime(date);
        //        series.setCreateUser(userId);
        //        series.setTag(tag);
        //        oaVehicleSeriesMapper.insert(series);
        //    }
        //}
        //return Rv.wrap(EErrorCode.success);
        return null;
    }

    public List<OaVehicleSeries> getVehicleSeriesList(List<String> codeList) {
        QueryWrapper<OaVehicleSeries> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(OaVehicleSeries.CODE, codeList);
        return oaVehicleSeriesMapper.selectList(queryWrapper);
    }

    /**
     * 取消关联
     *
     * @return
     */
    @Override
    public Rv getVehicleSeriesCancel(VehicleBrandParam vehicleBrandParam) {
        List<String> codeList = vehicleBrandParam.getCodeList();
        if (codeList == null || codeList.isEmpty()) {
            throw PangException.create(EErrorCode.selectCars);
        }
        QueryWrapper<OaSysVehicle> vehicleQueryWrapper = new QueryWrapper<>();
        vehicleQueryWrapper.in(OaSysVehicle.CODE, vehicleBrandParam.getCodeList());
        List<OaSysVehicle> vehicleList = oaSysVehicleMapper.selectList(vehicleQueryWrapper);
        if (!vehicleList.isEmpty()) {
            throw PangException.create(EErrorCode.usedSelectCars);
        }
        QueryWrapper<OaVehicleSeries> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(OaVehicleSeries.CODE, vehicleBrandParam.getCodeList());
        oaVehicleSeriesMapper.delete(queryWrapper);
        return Rv.wrap(EErrorCode.deleteSuccess);
    }

    /**
     * 获取运力类型
     *
     * @return
     */
    @Override
    public Rv getRequireLevel() {
        QueryWrapper<OaSysDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysDict.TYPE, "require_level");
        List<OaSysDict> oaSysDicts = oaSysDictMapper.selectList(queryWrapper);
        return Rv.wrap(EErrorCode.success, oaSysDicts);
    }

    /**
     * 获取所有车辆
     *
     * @return
     */
    @Override
    public Rv getAllVehicle() {
        QueryWrapper<OaSysVehicleMdict> queryWrapper = new QueryWrapper<>();
        List<OaSysVehicleMdict> oaSysVehicleMdicts = oaSysVehicleMdictMapper.selectList(queryWrapper);
        List<Map<String, Object>> menuMapList = ListToTreeUtil.getVehicleMdictList(oaSysVehicleMdicts);
        //转成树
        JSONArray menuResultList = ListToTreeUtil.listToTree(JSONArray.parseArray(JSON.toJSONString(menuMapList)), "id", "pId", "children");
        return Rv.wrap(EErrorCode.success, menuResultList);
    }

    /**
     * 修改车型信息
     *
     * @param vehicleTypeSeries
     * @return
     */
    @Override
    @Transactional
    public Rv updateVehicleType(VehicleTypeSeries vehicleTypeSeries) {
        OaSysVehicleMdict oaSysVehicleMdict = new OaSysVehicleMdict();
        oaSysVehicleMdict.setMdictId(Long.valueOf(vehicleTypeSeries.getMdictId()));
        oaSysVehicleMdict.setVehSeatsNumber(vehicleTypeSeries.getVehSeatsNumber());
        oaSysVehicleMdict.setVehicleType(Integer.valueOf(vehicleTypeSeries.getVehicleType()));
        oaSysVehicleMdict.setIsRelation(Integer.valueOf(vehicleTypeSeries.getIsRelation()));
        int i = oaSysVehicleMdictMapper.updateById(oaSysVehicleMdict);
        QueryWrapper<OaSysVehicle> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq(OaSysVehicle.CODE,vehicleTypeSeries.getCode());
        List<OaSysVehicle> oaSysVehicles = oaSysVehicleMapper.selectList(queryWrapper);
        long userId = TokenUtil.getTokenUserId();
        for (int j = 0; j < oaSysVehicles.size(); j++) {
            OaSysVehicle oaSysVehicle=oaSysVehicles.get(j);
            oaSysVehicle.setVehType(Integer.valueOf(vehicleTypeSeries.getVehicleType()));
            oaSysVehicle.setUpdateTime(new Date());
            oaSysVehicle.setUpdateUser(userId);
            oaSysVehicleMapper.updateById(oaSysVehicle);
        }
        return Rv.wrap(EErrorCode.success, i);
    }

    @Override
    public Rv exportVehicleType() {
        //List<VehicleSeries> vehicleSeriesList = oaVehicleSeriesMapper.getVehicleSeriesList("", "");
        //List<String> codeList = new ArrayList<>();
        //List<VehicleTypeSeries> seriesList = new ArrayList<>();
        //if (vehicleSeriesList.isEmpty()) {
        //    return Rv.wrap(EErrorCode.success, "");
        //}
        //for (VehicleSeries series : vehicleSeriesList) {
        //    codeList.add(series.getCode());
        //}
        //// 根部的集合
        //QueryWrapper dictWrapperMdict = new QueryWrapper();
        //dictWrapperMdict.orderByDesc(OaSysVehicleMdict.CREATE_TIME);
        //dictWrapperMdict.in(OaSysVehicleMdict.CODE, codeList);
        //List<OaSysVehicleMdict> list = oaSysVehicleMdictMapper.selectList(dictWrapperMdict);
        //List<OaSysVehicleMdict> oaSysVehicleMdictList = list;
        //List<String> parentIdList = new ArrayList<>();
        //for (OaSysVehicleMdict dict : oaSysVehicleMdictList) {
        //    parentIdList.add(dict.getParentId());
        //}
        //// 根部的父节点集合
        //QueryWrapper<OaSysVehicleMdict> dictParentWrapperMdict = new QueryWrapper<>();
        //dictParentWrapperMdict.in(OaSysVehicleMdict.MDICT_ID, parentIdList);
        //List<OaSysVehicleMdict> dictParentList = oaSysVehicleMdictMapper.selectList(dictParentWrapperMdict);
        //// 全部的
        //QueryWrapper<OaSysVehicleMdict> queryWrapperMdict = new QueryWrapper<>();
        //List<OaSysVehicleMdict> allOaSysVehicleMdict = oaSysVehicleMdictMapper.selectList(queryWrapperMdict);
        //
        //for (OaSysVehicleMdict vehicle : oaSysVehicleMdictList) {
        //    VehicleTypeSeries series = new VehicleTypeSeries();
        //    if (CheckUtil.objIsNotEmpty(vehicle.getUpdateTime())) {
        //        series.setUpdateTime(DateFormatUtils.format(vehicle.getUpdateTime(), "yyyy-MM-dd HH:mm:ss"));
        //    } else {
        //        series.setUpdateTime("");
        //    }
        //    series.setParentId(String.valueOf(vehicle.getParentId()));
        //    series.setCode(vehicle.getCode());
        //    series.setName(vehicle.getName());
        //    for (OaSysVehicleMdict dict : dictParentList) {
        //        if (vehicle.getParentId().equals(String.valueOf(dict.getMdictId()))) {
        //            series.setModels(dict.getName());
        //            for (OaSysVehicleMdict all : allOaSysVehicleMdict) {
        //                if (dict.getParentId().equals(String.valueOf(all.getMdictId()))) {
        //                    series.setBrand(all.getName());
        //                    break;
        //                }
        //            }
        //            break;
        //        }
        //    }
        //    seriesList.add(series);
        //}
        //
        //for (int i = 0; i < seriesList.size(); i++) {
        //    for (int j = 0; j < vehicleSeriesList.size(); j++) {
        //        if (seriesList.get(i).getCode().equals(vehicleSeriesList.get(j).getCode())) {
        //            seriesList.get(i).setVehSeatsNumber(vehicleSeriesList.get(j).getVehSeatsNumber());
        //            seriesList.get(i).setLinkedId(vehicleSeriesList.get(j).getLinkedId());
        //            seriesList.get(i).setLabel(vehicleSeriesList.get(j).getLabel());
        //            seriesList.get(i).setVehicleType(String.valueOf(vehicleSeriesList.get(j).getVehicleType()));
        //        }
        //    }
        //}
        //return Rv.wrap(EErrorCode.success, seriesList);
        return null;
    }

    /**
     * 汉字转换成汉语拼音全拼，英文字符不变
     *
     * @param chinese 汉字
     * @return 拼音
     * @author you chou
     */
    private String convertChineseToFullSpell(String chinese) {
        String CHINESE_PATTERN = "[\u4e00-\u9fa5]";
        String pinyinName = "";
        char[] nameChar = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
        for (int i = 0; i < nameChar.length; i++) {
            if (Pattern.matches(CHINESE_PATTERN, nameChar[i] + "")) {
                try {
                    pinyinName += PinyinHelper.toHanyuPinyinStringArray(
                            nameChar[i], defaultFormat)[0];
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    throw PangException.create(EErrorCode.dataParseError);
                }
            } else {
                pinyinName += nameChar[i];
            }
        }
        return pinyinName;
    }



}
